/*
* create-keyframe-animation是异步运行的
* 如果要同时实现两个动画，请传入不同的name以区别
*
* */

import animations from 'create-keyframe-animation'
import { getStyle } from 'common/js/dom'

export function scrollText(el, name = 'scroll') {
    // 判断是否以及添加过滚动
    let check = el.getElementsByClassName('_subtext_')
    if (check.length > 0) {
        return
    }

    let child = el.getElementsByClassName('scroll-text')[0]
    const PWidth = el.offsetWidth
    let CWidth = child.offsetWidth

    if (CWidth <= PWidth) {
        animations.unregisterAnimation(name)
        getStyle(child, 'animation', '')
        return
    }

    child.innerHTML += `<span class="_subtext_" style="margin-left: 30px">${child.innerHTML}</span>`
    CWidth += 30
    // 定义动画参数
    let animation = {
        0: {
            transform: `translate3d(0, 0, 0)`
        },
        80: {
            transform: `translate3d(-${CWidth}px, 0, 0)`
        },
        100: {
            transform: `translate3d(-${CWidth}px, 0, 0)`
        }
    }

    // 使得滚动适应不同宽度
    const scrollTime = CWidth * 32

    // 注册css3动画插件
    animations.registerAnimation({
        name,
        animation,
        presets: {
            // 动画持续时间
            duration: scrollTime,
            delay: 2000,
            // 缓动函数
            easing: 'linear',
            iterations: 'infinite'
        }
    })

    // 运行动画
    animations.runAnimation(child, name)
}
